/**
 * @desc 持仓管理真实组合组件
 */
import { PureComponent } from 'react';
import moment from 'moment/moment';
import { DownOutlined, RightOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Button, Dropdown, Menu, Popover, Spin, Tree } from 'antd';
import { connect, routerRedux } from 'dva';
import { AdvancedSearch, codeType, DATA_ENTRY, PrimaryC, PrimaryGhostC, TableC } from '../../../../../../comps';
import myStyle from './index.less';
import { exportFile } from '../../../../../../utils/commonFunc';
import uuid from 'es6-uuid';
import accounting from 'accounting';
import config from '@/src/comps/business/tradingMarket/config';

const filterArr = ['BOOKKEEPING_MODE', 'COMMAND_MODE'];
@Form.create()
@connect(({ loading, workStationM }) => ({ loading, workStationM }))
export default class RealHoldManage extends PureComponent {
  constructor(props) {
    super(props);

    this.state = {
      columns: [],
      visible: false,
      currentPage: 1, // 页码
      pageSize: 10, // 每页数量
      total: 0,
      // 真实组合请求参数
      realParams: {
        date: moment().format('YYYY-MM-DD'),
        // 产品的 组合代码 应该是取id或者key而不是code
        portfolioId: '',
      },
      realTotalDataSource: [], // 获取统计表格-第一栏
      realStatisticsInfo: {}, // 中间统计信息-第二栏
      realDataSource: [], // 持仓查询 真实组合 - 第三栏
      isShowAddTransaction: undefined, // 是否展示添加交易
      checkedKeys: [], // 选中的keys
      PopoverOpen: false, // 是否显示多选
      currentShowColumn: [], // 当前显示的column
    };
  }

  UNSAFE_componentWillReceiveProps(nextProps) {
    // if (this.props.productCode !== nextProps.productCode) {
    //   const date = this.dateRef.props.form.getFieldsValue().date;
    //
    //   this.setState(
    //     {
    //       realParams: {
    //         portfolioId: nextProps.workStationM.CombinationType.portfolioId,
    //         date: date
    //           ? moment(date).format("YYYY-MM-DD")
    //           : moment().format("YYYY-MM-DD"),
    //       },
    //       isProductCodeUndefined: nextProps.productCode,
    //     },
    //     () => {
    //       if (nextProps.productCode === undefined) {
    //         // this.dateRef.setDate(moment())
    //       }
    //       console.log(222222222)
    //       this.getRealData();
    //     }
    //   );
    // }

    // 产品卡片虚拟转真实不会改变  持仓卡片组合虚拟转真实就会变
    // 拦截portfolioCode变化
    const { date } = this.dateRef.props.form.getFieldsValue();
    if (nextProps.workStationM.CombinationType.portfolioCode != this.props.workStationM.CombinationType.portfolioCode) {
      const { CombinationType } = nextProps.workStationM;
      // 获取mode显示隐藏添加按钮
      this.getMode(CombinationType.productId);
      // 检测产品点击变化
      if (nextProps.workStationM.CombinationType) {
        this.setState(
          {
            realParams: {
              portfolioId: CombinationType.portfolioId,
              date: date ? moment(date).format('YYYY-MM-DD') : moment().format('YYYY-MM-DD'),
            },
            isProductCodeUndefined: nextProps.productCode,
          },
          () => {
            this.getRealData();
          },
        );
      }
    }
  }

  componentDidMount() {
    this.changeDate(undefined, true);
    this.props.onRef(this);
    // // 进入页面设置realParams
    // this.setState({
    //   realParams: {
    //     portfolioId: this.props.workStationM.CombinationType.portfolioId,
    //     date: moment().format('YYYY-MM-DD'),
    //   },
    //   isProductCodeUndefined: true
    // }, () => this.getRealData())
    // 进入页面获取Mode
    this.getMode(this.props.workStationM.CombinationType.productId);
    const { date } = this.dateRef.props.form.getFieldsValue();
    if (this.props.productCode || this.props.workStationM.CombinationType) {
      this.setState(
        {
          realParams: {
            portfolioId: this.props.workStationM.CombinationType.portfolioId,
            date: date ? moment(date).format('YYYY-MM-DD') : moment().format('YYYY-MM-DD'),
          },
          productCode: this.props.workStationM.CombinationType.portfolioCode,
          isProductCodeUndefined: true,
        },
        () => {
          this.getRealData();
        },
      );
    }
  }

  getRealData(type) {
    const { tradingCode, exchangeCode, productCode } = this.state.realParams;
    if (type !== 'handleTableChange') {
      // 获取统计表格-第一栏
      // 处理get请求 参数设置undefined不会自动去除
      const paramsForQueryRealListByGET = {
        ...this.state.realParams,
        portfolioId: this.props.workStationM.CombinationType.portfolioCode,
        date: this.state.realParams.date ? this.state.realParams.date : moment().format('YYYY-MM-DD'),
      };
      if (paramsForQueryRealListByGET.exchangeCode == undefined || paramsForQueryRealListByGET.tradingCode == undefined) {
        delete paramsForQueryRealListByGET.exchangeCode;
        delete paramsForQueryRealListByGET.tradingCode;
      }
      // 有时间在查询
      if (paramsForQueryRealListByGET.date) {
        this.props.dispatch({
          type: 'workStationM/queryRealList',
          payload: paramsForQueryRealListByGET,
          callback: (data) => {
            this.setState({
              realTotalDataSource: data || [],
            });
          },
        });
      }

      // 获取中间统计数据-第二栏
      this.props.dispatch({
        type: 'workStationM/getSearchReal',
        payload: {
          dataDt: this.state.realParams.date ? this.state.realParams.date : moment().format('YYYY-MM-DD'),
          timestamp: Number(new Date()),
          type: '15',
          isHkStk: '0',
          tradingCode,
          // 交易市场
          exchangeCode,
          fundId: this.state.isProductCodeUndefined === undefined ? undefined : [this.state.realParams.portfolioId],
        },
        callback: (data) => {
          this.setState({
            realStatisticsInfo: data,
          });
        },
      });
    }

    // 获取真实获取持仓管理列表Table - 第三栏
    this.props.dispatch({
      type: 'workStationM/getStockTable',
      payload: {
        pageSize: this.state.pageSize,
        page: this.state.currentPage,
        dataDt: this.state.realParams.date ? this.state.realParams.date : moment().format('YYYY-MM-DD'),
        timestamp: Number(new Date()),
        isHkStk: '0',
        searchType: 'pt',
        trdAttr: 'PT',
        type: 'barra',
        tradingCode,
        // 交易市场
        exchangeCode,
        fundId: this.state.isProductCodeUndefined === undefined ? undefined : [this.state.realParams.portfolioId],
      },
      callback: (res) => {
        this.setState({
          realDataSource: res.data,
          total: res.total,
        });
      },
    });
    if (type == 'searchDocker' || type == 'handleTableChange') {
    } else {
      // 真实表头
      this.getColumn();
    }
  }

  // 获取表头
  getColumn = () => {
    this.props.dispatch({
      type: 'workStationM/queryShowCol',
      payload: { type: 'TRADE_ANA_STK_HOLD_INFO_BARRA', isHkStk: 0 },
      callback: (data) => {
        const copyColumn = _.cloneDeep(data);
        copyColumn.map((v) => {
          if (v.key == 'lCurrentAmount') {
            v.type = 'number';
          }
          if (v.key === 'tradingcode') {
            v.render = (text, record) => {
              if (record?.id.exchangecode) {
                const findvalue = config.filter((item) => {
                  return item.value == record.id.exchangecode;
                });
                if (findvalue && findvalue.length > 0) {
                  return text ? `${text}.${findvalue[0].abbr}` : '--';
                } else {
                  return '--';
                }
              } else {
                return '--';
              }
            };
          }
          if (
            v.key == 'costPrice' ||
            v.key == 'costPriceCn' ||
            v.key == 'efProportion' ||
            v.key == 'enFloatProfit' ||
            v.key == 'enFloatProfitCn' ||
            v.key == 'mValue' ||
            v.key == 'mValueCn' ||
            v.key == 'buyRate'
          ) {
            v.type = 'money';
          }
          if (v.key == 'enLastPrice') {
            v.type = 'money';
            v.width = 200;
          }
          if (v.dataIndex === 'enLastPrice') {
            v.width = 140;
          }
          if (v.dataIndex === 'weight') {
            v.render = (text) => {
              return accounting.formatNumber(Math.round(text * 10000) / 100, 2) ?? '--';
            };
          }
        });
        this.setState({
          columns: copyColumn,
          currentShowColumn: copyColumn.filter((i) => i.display),
          checkedKeys: copyColumn.filter((i) => i.display).map((v) => v.key),
        });
      },
    });
  };

  // 获取Modes判断交易按钮显示
  getMode(id) {
    this.props.dispatch({
      type: 'workStationM/getModeByid',
      payload: { id },
      callback: (data) => {
        if (data.length > 0) {
          const a = data[0].baseInfo.modes;
          this.setState({
            isShowAddTransaction: a,
          });
        }
      },
    });
  }

  searchDocker = (e) => {
    if (e) {
      const { date, exchangeCode, tradingCode } = e;
      this.setState(
        {
          realParams: {
            ...this.state.realParams,
            date: moment(date).format('YYYY-MM-DD'),
            // 证券代码
            tradingCode: tradingCode || undefined,
            // 交易市场
            exchangeCode: exchangeCode || undefined,
          },
        },
        () => this.getRealData('searchDocker'),
      );
    } else {
      const copy = JSON.parse(JSON.stringify(this.state.realParams));
      this.setState(
        {
          realParams: {
            ...this.state.realParams,
            date: moment().format('YYYY-MM-DD'),
            exchangeCode: undefined,
            tradingCode: undefined,
          },
        },
        () => {
          const { date, tradingCode, exchangeCode } = this.state.realParams;
          if (copy.date !== date || copy.exchangeCode !== exchangeCode || copy.tradingCode !== tradingCode) {
            this.getRealData('searchDocker');
          }
        },
      );
    }
  };

  // 更多操作
  handleVisibleChange = (flag) => {
    this.setState({ visible: flag, PopoverOpen: false });
  };

  onSelect = (selectedKeys) => {
    const { columns } = this.state;
    const copyColumns = _.cloneDeep(columns);
    const currentShowColumn = [];
    // 筛选参数
    copyColumns.map((v) => {
      v.display = false;
      selectedKeys.map((i) => {
        if (v.key == i) {
          v.display = true;
        }
      });
    });
    // 筛选column同步显示
    copyColumns.map((v) => {
      selectedKeys.map((i) => {
        if (v.key == i) {
          currentShowColumn.push(v);
        }
      });
    });
    this.setState({
      checkedKeys: selectedKeys,
      columnsP: copyColumns,
      currentShowColumn,
    });
  };

  // 确认保存column到云端
  sureSaveCol = () => {
    this.props.dispatch({
      type: 'workStationM/saveCol',
      payload: {
        columns: this.state.columnsP ?? this.state.columns,
        type: 'TRADE_ANA_STK_HOLD_INFO_BARRA',
        isHkStk: '0',
      },
      callback: (res) => {
        if (res.code === 0) {
          this.setState({
            PopoverOpen: false,
            visible: false,
          });
          this.getColumn();
        }
      },
    });
  };

  // 更多
  menuReal = () => {
    const { columns, checkedKeys } = this.state;
    return (
      <Menu onClick={this.handleMenuClickReal}>
        <Menu.Item key='more'>更多持仓</Menu.Item>
        <Menu.Item key='export'>导出</Menu.Item>
        <Menu.Item key='column'>
          <Popover
            placement='leftTop'
            visible={this.state.PopoverOpen}
            title={
              <Tree
                treeData={[
                  {
                    key: 'all',
                    title: '全部',
                    children: columns,
                  },
                ]}
                checkable={true}
                defaultExpandAll={true}
                checkedKeys={checkedKeys}
                onCheck={this.onSelect}
              />
            }
            content={
              <div>
                <PrimaryC title='确定' onClick={this.sureSaveCol} />
                <PrimaryGhostC
                  title='取消'
                  style={{ marginLeft: '10px' }}
                  onClick={() => {
                    this.getColumn();
                    this.setState({
                      PopoverOpen: false,
                      visible: false,
                    });
                  }}
                />
              </div>
            }
            trigger='click'
            onVisibleChange={(v) => {
              this.setState({
                PopoverOpen: v,
              });
            }}
          >
            <div>
              列选择
              <RightOutlined style={{ float: 'right', marginTop: '4px' }} />
            </div>
          </Popover>
        </Menu.Item>
      </Menu>
    );
  };

  // 表格页码响应
  handleTableChange = (pagination) => {
    const { current, pageSize } = pagination;
    this.setState(
      {
        currentPage: current,
        pageSize,
      },
      () => {
        this.getRealData('handleTableChange');
      },
    );
  };

  realPoolImport = () => {
    exportFile('api/v1/tradeAnaStkHoldInfo/exportStk', {
      dataDt: this.state.realParams.date,
      timestamp: Number(new Date()),
      isHkStk: '0',
      searchType: 'pt',
      type: 'barra',
      fundId: this.state.realParams.portfolioId,
    });
  };

  // 更多持仓
  more = () => {
    const positionquery = {
      HkStkType: '1', // 0-普通股票  1-港股
      activeKey: 'Stock',
      dataDt: this.state.realParams.date,
      fundId: this.state.isProductCodeUndefined === undefined ? undefined : [this.state.realParams.portfolioId],
      exchangeCodeObj: this.state.securityType,
    };
    sessionStorage.setItem('portfolioTracking', JSON.stringify(positionquery));
    this.props.dispatch(routerRedux.push(`/composite/positionquery`));
  };

  handleMenuClickReal = (e) => {
    switch (e.key) {
      case 'more':
        this.more();
        break;
      case 'export':
        this.realPoolImport();
        break;
      default:
        () => {};
        break;
    }
    if (e.key !== 'column') {
      this.setState({ visible: false });
    }
  };

  // 添加交易 调用changePage（3， type）
  addTransac = () => {
    this.props.changePage(3, this.state.isShowAddTransaction);
  };

  zqCodeChange = (e) => {
    if (e && e.securityType) {
      this.setState({
        securityType: e,
      });
    } else {
      this.setState({
        securityType: undefined,
      });
    }
  };

  changeDate = (e, isFirst = false) => {
    // 判断是否为节假日 当选择节假日后，【添加交易】按钮置灰，用户不能进行交易；其他保持不变\
    const startDate = isFirst ? moment().startOf('month').format('YYYY-MM-DD') : moment(e).startOf('month').format('YYYY-MM-DD');
    const endDate = isFirst ? moment().endOf('month').format('YYYY-MM-DD') : moment(e).endOf('month').format('YYYY-MM-DD');
    const day = isFirst ? parseInt(moment().format('DD')) - 1 : parseInt(moment(e).format('DD')) - 1;
    this.props.dispatch({
      type: 'globalM/queryHoliday',
      payload: {
        startDate,
        endDate,
        calendarType: 1,
      },
      callback: (type, data) => {
        if (type == 'success') {
          // console.log(data);
          this.setState({
            isHoliday: data[day].isHoliday,
          });
        }
      },
    });
  };

  render() {
    const { realTotalDataSource, isShowAddTransaction, visible, columns, currentPage, pageSize, realDataSource, currentShowColumn } = this.state;
    const { loading } = this.props;
    // 设置scroll x
    if (columns && columns.length > 8) {
      const a = columns.length;
      this.scrollx = a * 150;
    } else {
      this.scrollx = 0;
    }
    return (
      <div className={myStyle.realHoldManage}>
        {/* 查询栏 */}
        <div className={myStyle.searchRealHold}>
          <AdvancedSearch
            onQuery={(e) => {
              this.searchDocker(e);
            }}
            onClear={(e) => {
              this.searchDocker(e);
            }}
            dataSource={[
              {
                dataIndex: 'date',
                title: '日期',
                type: DATA_ENTRY.SINGLEDATE,
                initialValue: moment(),
                formItemLayout: {
                  labelCol: {
                    span: this.props.showOnly ? 2 : 6,
                  },
                  wrapperCol: {
                    span: 15,
                  },
                },
                disableEnd: moment(new Date()).add(1, 'days'),
                onRef: (ref) => (this.dateRef = ref),
                allowClear: false,
                onChange: (e) => this.changeDate(e),
              },
              {
                dataIndex: 'tradingCode',
                codeType: codeType.positioned,
                type: DATA_ENTRY.SECURITIESCODE,
                onChange: (e) => this.zqCodeChange(e),
              },
            ]}
          />
        </div>
        {/* 统计表格 */}
        <div className={''}>
          <Spin spinning={this.props.loading.effects['workStationM/queryRealList']}>
            <div className={myStyle.wrapReal}>
              <div>
                <span style={{ marginRight: 15 }}>类别</span>
                <span style={{ marginRight: 15 }}>权重(%)</span>
                <span style={{ marginRight: 15 }}>持仓市值</span>
                <span style={{ marginRight: 15 }}>浮动盈亏</span>
                <span style={{ marginRight: 15 }}>总盈亏</span>
                <span style={{ marginRight: 15 }}>当日盈亏</span>
              </div>
              {realTotalDataSource && realTotalDataSource.length ? (
                <>
                  {realTotalDataSource.map((item, key) => {
                    return (
                      <div>
                        <span style={{ marginRight: 15 }}>{item.statisticaType ?? '--'}</span>
                        <span style={{ marginRight: 15 }}>{accounting.formatNumber(parseInt(Number(item.weight) * 10000) / 100, 2) ?? '--'}</span>
                        <span style={{ marginRight: 15 }}>
                          {isNaN(Number(item.positionPrice)) ? '--' : Number(item.positionPrice) === 0 ? '--' : accounting.formatNumber(Number(item.positionPrice), 2)}
                        </span>
                        <span style={{ marginRight: 15 }}>
                          {isNaN(Number(item.enFloatProfit)) ? '--' : Number(item.enFloatProfit) === 0 ? '--' : accounting.formatNumber(Number(item.enFloatProfit), 2)}
                        </span>
                        <span style={{ marginRight: 15 }}>
                          {isNaN(Number(item.totalProfitAndLoss))
                            ? '--'
                            : Number(item.totalProfitAndLoss) === 0
                            ? '--'
                            : accounting.formatNumber(Number(item.totalProfitAndLoss), 2)}
                        </span>
                        <span style={{ marginRight: 15 }}>
                          {isNaN(Number(item.totalProfitAndLoss))
                            ? '--'
                            : Number(item.totalProfitAndLoss) === 0
                            ? '--'
                            : accounting.formatNumber(Number(item.totalProfitAndLoss), 2)}
                        </span>
                      </div>
                    );
                  })}
                </>
              ) : null}
            </div>
          </Spin>
        </div>
        {/* 中间的统计信息 & 操作按钮 */}
        <div className={myStyle.displayOperate}>
          <div>
            <div>
              资产市值：
              {isNaN(Number(this.state.realStatisticsInfo?.marketValue)?.toFixed(2)) ? '--' : accounting.formatNumber(Number(this.state.realStatisticsInfo?.marketValue), 2)}
            </div>
            <div>
              浮动盈亏：
              {isNaN(Number(this.state.realStatisticsInfo?.enFloatProfit)?.toFixed(2)) ? '--' : accounting.formatNumber(Number(this.state.realStatisticsInfo?.enFloatProfit), 2)}
            </div>
            <div>
              总盈亏：
              {/* 先写死后续maat那边字段加了之后 这边会放开计算的 */}
              {'--'}
              {/* {isNaN( */}
              {/*  Number(this.state.realStatisticsInfo?.totalProfit)?.toFixed(2) */}
              {/* ) */}
              {/*  ? "--" */}
              {/*  : accounting.formatNumber( */}
              {/*      Number(this.state.realStatisticsInfo?.totalProfit), */}
              {/*      2 */}
              {/*    )} */}
            </div>
            <div>
              当日盈亏：
              {/* 先写死后续maat那边字段加了之后 这边会放开计算的 */}
              {'--'}
              {/* {isNaN( */}
              {/*  Number(this.state.realStatisticsInfo?.marketValue)?.toFixed(2) */}
              {/* ) */}
              {/*  ? "--" */}
              {/*  : accounting.formatNumber( */}
              {/*      Number(this.state.realStatisticsInfo?.marketValue), */}
              {/*      2 */}
              {/*    )} */}
            </div>
          </div>
          <div>
            {filterArr.includes(isShowAddTransaction) ? <PrimaryC disabled={this.state.isHoliday == 0} onClick={() => this.addTransac()} title={'添加交易'} /> : null}

            <div className={myStyle.moreOperationSec}>
              <Dropdown overlay={this.menuReal} onVisibleChange={this.handleVisibleChange} visible={visible} trigger={['click']}>
                <Button>
                  更多操作 <DownOutlined />
                </Button>
              </Dropdown>
            </div>
          </div>
        </div>
        <div className={myStyle.table}>
          <TableC
            columns={columns.filter((i) => i.display) || []}
            dataSource={realDataSource || []}
            onChange={this.handleTableChange}
            scroll={{ x: this.scrollx, y: 80 }}
            loading={loading.effects['workStationM/getStockTable']}
            rowKey={`tradingcode${uuid}`}
            current={currentPage}
            pageSize={pageSize}
            size={'small'}
            total={this.state.total}
            hidePage={currentShowColumn.length === 0}
          />
        </div>
      </div>
    );
  }
}
